package com.serena.da.rest.services.security;

import org.json.JSONArray;
import org.json.JSONObject;
import com.serena.da.rest.http_helpers.Response;
import com.serena.da.rest.services.SraService;

/**
 * Created by Spitkovskyi Igor on 8/10/2014.
 */
public class SraSecurityService extends SraService {
    private final String SERVICE_NAME = "security/";

    private final String METHOD_SCHEMA = "schema/";

    private final String TARGET_ROLES = "roles";

    private static SraSecurityService securityService;

    protected SraSecurityService() throws Exception {
        super();
    }

    public static SraSecurityService getInstance() throws Exception{
        if(securityService == null){
            securityService = new SraSecurityService();
        }
        return securityService;
    }

    public String getSecuritySchemas() {
        //localhost:8081/serena_ra/rest/security/schema
        String url = getRestUrl(SERVICE_NAME + METHOD_SCHEMA, false);
        Response response;
        //GetRequest req = new GetRequest(url);
        try {
            response = executeRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return response.getResponseBody();
    }

    public String getSecuritySchemaID(String SchemaName) {
        String existingSchemas = getSecuritySchemas();
        JSONArray schemas = new JSONArray(existingSchemas);
        for (int i = 0; i < schemas.length(); i++) {
            JSONObject schema = schemas.getJSONObject(i);
            if (schema.getString("name").equalsIgnoreCase(SchemaName)) {
                return schema.getString("id");
            }
        }
        return null;
    }

    public String getSecurityRolesFromSchema(String SchemaID) {
        //localhost:8081/serena_ra/rest/security/schema/20000000000000000000000000000015/roles
        String url = getRestUrl(SERVICE_NAME + METHOD_SCHEMA + SchemaID + "/" + TARGET_ROLES, false);
        Response response;
        //GetRequest req = new GetRequest(url);
        try {
            response = executeRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return response.getResponseBody();
    }

    public String getSecurityRoleID(String SecuritySchemaName, String RoleName) {
        String schemaID = getSecuritySchemaID(SecuritySchemaName);
        String securityRoles = getSecurityRolesFromSchema(schemaID);
        JSONArray roles = new JSONArray(securityRoles);
        for (int i = 0; i < roles.length(); i++) {
            JSONObject role = roles.getJSONObject(i);
            if (role.getString("name").equalsIgnoreCase(RoleName)) {
                return role.getString("id");
            }
        }
        return null;
    }
}
